<template>
  <div>
    <sunSearch :search="searchList" />
    <el-card class="sun-el-card">
      <sunUpdataAdd :title="this.$route.meta.title" />
      <el-table v-loading="listLoading" :header-cell-style="{color:'#000000'}" :data="list" border fit highlight-current-row>
        <!-- <el-table-column align="center" label="ID" prop="id" width="80" /> -->
        <el-table-column label="姓名" prop="name" />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="联系电话" prop="mobile" />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.enable_status ? '启用' : '禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" prop="created_at" width="200" />
        <el-table-column align="center" label="更新时间" prop="updated_at" width="200" />
        <el-table-column align="center" label="操作" width="350">
          <template slot-scope="scope">
            <el-button type="danger" :disabled="scope.row.id === 1" size="small" @click="removeData(scope.row.id)">
              删除
            </el-button>
            <el-button type="primary" :disabled="scope.row.id === 1" size="small" @click="addData(scope.row)">
              编辑
            </el-button>
            <el-button type="primary" :disabled="scope.row.id === 1 || scope.row.super_admin === 1" size="small" @click="setRoles(scope.row)">
              分配角色
            </el-button>
            <el-button type="primary" :disabled="scope.row.id === 1 || scope.row.super_admin === 1" size="small" @click="setPermissions(scope.row)">
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="laypage.total>0" :total="laypage.total" :page.sync="laypage.number" :limit.sync="laypage.size" @pagination="requestData" />
    </el-card>
    <el-dialog
      width="600px"
      class="sun-el-dialog"
      :destroy-on-close="true"
      :lock-scroll="true"
      :close-on-click-modal="false"
      :show-close="false"
      :visible.sync="showPopout"
    >
      <el-form ref="refForm" :model="formData">
        <el-form-item
          label="姓名"
          prop="name"
          :rules="[
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ]"
        >
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item
          label="用户名"
          prop="username"
          :rules="[
            { required: true, message: '请输入用户名', trigger: 'blur' },
          ]"
        >
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item
          label="密码"
          prop="password"
          :rules="[
            { required: !is_edit, message: '请设置登录密码', trigger: 'blur' },
          ]"
        >
          <el-input v-model="formData.password" placeholder="请设置输入密码" />
        </el-form-item>

        <el-form-item
          label="联系电话"
          prop="mobile"
          :rules="[
            { required: true, message: '请输入联系电话', trigger: 'blur' },
          ]"
        >
          <el-input v-model="formData.mobile" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item
          label="超级管理员"
        >
          <el-switch
            v-model="formData.super_admin"
            class="tableScopeSwitch"
            :active-value="true"
            :inactive-value="false"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>

        <el-form-item
          label="状态"
          :rules="[
            { required: true, message: '请输入设置状态', trigger: 'blur' },
          ]"
        >
          <el-switch
            v-model="formData.enable_status"
            class="tableScopeSwitch"
            :active-value="true"
            :inactive-value="false"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showPopout = false">取 消</el-button>
        <el-button type="primary" size="small" @click="onFinish">完 成</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-drawer
      class="sun-el-drawer"
      :with-header="false"
      :destroy-on-close="true"
      :wrapper-closable="false"
      :visible.sync="show_roles"
      direction="rtl"
    >
      <roles />
    </el-drawer>
    <!-- 查看权限 -->
    <el-drawer
      class="sun-el-drawer"
      :with-header="false"
      :destroy-on-close="true"
      :wrapper-closable="false"
      :visible.sync="show_checkPermissions"
      direction="rtl"
    >
      <checkPermissions />
    </el-drawer>
    <!-- 分配权限 -->
    <el-drawer
      class="sun-el-drawer"
      :with-header="false"
      :destroy-on-close="true"
      :wrapper-closable="false"
      :visible.sync="show_permissions"
      direction="rtl"
    >
      <permissions />
    </el-drawer>
  </div>
</template>

<script>
import { get, put, post } from '@/api/request'
import { $remove, $tooltips } from '@/sun-components/SunMsg.js'
import Pagination from '@/sun-components/Pagination'
import SunSearch from '@/sun-components/SunSearch'
import SunUpdataAdd from '@/sun-components/SunUpdataAdd'
import Permissions from './components/permissions'
import Roles from './components/roles'
import CheckPermissions from './components/checkPermissions'

export default {
  name: 'Admin',
  components: { Pagination, SunSearch, SunUpdataAdd, Permissions, Roles, CheckPermissions },
  data() {
    return {
      searchList: [
        { 'id': 'ID', type: 'input', show: 'id', value: '' },
        { 'name': '姓名', type: 'input', show: 'name', value: '' },
        { 'username': '昵称', type: 'input', show: 'username', value: '' },
        { 'mobile': '电话', type: 'input', show: 'mobile', value: '' }
      ],
      searchFilter: {},
      showPopout: false,
      list: null,
      listLoading: true,
      laypage: {
        number: 1,
        size: 10,
        total: 0
      },
      formData: {
        id: '',
        name: '',
        username: '',
        password: '',
        mobile: '',
        enable_status: true,
        roles: [],
        super_admin: false
      },
      checkPermissions: {},
      permissionsList: [],
      rolesList: [],
      currentItem: null,
      show_permissions: false,
      show_roles: false,
      show_checkPermissions: false,
      is_edit: false
    }
  },
  created() {
    this.upData()
    this.getPermissions()
    this.getRoles()
  },
  methods: {
    upData() {
      this.requestData()
    },
    async getPermissions() {
      await get(`permissions`).then(response => {
        if (response.code === 0) {
          this.permissionsList = response.data
        }
      })
    },
    async getRoles() {
      await get(`roles`, {}, { all: 1 }).then(response => {
        if (response.code === 0) {
          this.rolesList = response.data
        }
      })
    },
    async setPermissions(row) {
      console.log('row', row)
      this.currentItem = row
      console.log(this.permissionsList)
      this.show_permissions = true
    },
    async setRoles(row) {
      this.currentItem = row
      console.log('row', row)
      console.log(this.rolesList)
      this.show_roles = true
    },
    addData(row) {
      this.is_edit = false
      if (row) {
        this.is_edit = true
        this.formData.id = JSON.stringify(row.id)
        this.formData.name = row.name
        this.formData.username = row.username
        this.formData.password = ''
        this.formData.mobile = row.mobile
        this.formData.enable_status = row.enable_status
        this.formData.super_admin = row.super_admin
      } else {
        this.formData.super_admin = false
      }
      this.showPopout = true
    },
    async searchResult(filter) {
      this.searchFilter = filter
      this.upData()
    },
    async onFinish() {
      const _that = this
      _that.$onFinishBox()
        .then((action) => {
          if (action) {
            const id = _that.formData.id ? _that.formData.id : false
            if (!/^1[3-9]\d{9}$/.test(_that.formData.mobile)) {
              $tooltips('请正确输入手机号')
              return false
            }
            if (id) {
              if (!_that.formData.password) delete _that.formData.password
              put(`admins/${id}`, _that.formData).then(response => {
                if (response.code === 0) {
                  _that.showPopout = false
                  _that.upData()
                }
              })
            } else {
              post(`admins`, _that.formData).then(response => {
                if (response.code === 0) {
                  _that.showPopout = false
                  _that.upData()
                }
              })
            }
          }
        })
        .catch((cancel) => {
          // 点击取消
        })
    },
    async removeData(id) {
      $remove(`admins/${id}`, this)
    },
    async requestData() {
      this.listLoading = true
      await get(`admins`, Object.assign(this.searchFilter, { 'page[size]': this.laypage.size, 'page[number]': this.laypage.number })).then(response => {
        if (response.code === 0) {
          response.data.forEach(item => {
            item['rolesId'] = []
            item.roles?.forEach(el => {
              item.rolesId.push(el.id)
            })
          })
          this.list = response.data
          this.laypage.total = response.meta.total
        }
        this.listLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '@/styles/sun-style.scss';
</style>
